import { useEffect, useRef} from 'react';

export default (
    fn: () => void,
    delay: number | null | undefined,
    options?: {
        immediate?: boolean
    }
): void => {
    const immediate = options?.immediate
    const timerRef = useRef(fn)
    timerRef.current = fn

    useEffect(() => {
        if (delay === undefined || delay === null) return
        if (immediate) {
            timerRef.current?.()
        }
        const timer = setInterval(() => {
            timerRef.current?.()
        }, delay)
        return () => {
            clearInterval(timer)
        }
    }, [delay])
}